#!/bin/sh
FUNCTIONS=functions

# Source Functions
. ./$FUNCTIONS

PROGNAME=`basename $0`
LOG=./$PROGNAME.log

#Server
BNINET_HOME=/home/bninet
BNI=$BNINET_HOME/bni
JBOSS_HOME=$BNINET_HOME/jbossas
INIT_DIR=/etc/init.d
BNI_CONF=$JBOSS_HOME/server/default/conf/bni
BNI_USER=bninet
SIM_IP=`/sbin/ifconfig -a | grep -v "127.0.0.1" | awk -F ":"  '/inet / {print $2}'  |cut -d" " -f1| tail -n 1`

#Commond
TAR="tar xzf"
WGET="wget -q"
RM="rm -f"

print_help()
{
  info "Usage $PROGNAME OPTIONS REQUIRED_ARGS"

  cat - <<EOF
where OPTIONS can be:
  -h|-H|--help  Prints (this) help message and exits
  -deploy       Deploys Annapurna Simulators to Specified Sim Host
  -X            Prints what operations would be executed, but does not execute them
  -jobPrefix    Used when we have branched build
and REQUIRED_ARGS are
  -sim          : VAL = IP address of the Sim node
  -sm           : VAL = IP address of the SM node
  -version      : VAL = Product Version
EOF
  exit 0
}


clean() 
{
  if [ ! -z "$NO_EXEC" ] ; then
    info "Skipping Operation: 'Clean'"
    info "Skipping Operation: $RM    $ANA_TAR_FILE"
    info "Skipping Operation: $RM -r $BNI"
    info "Skipping Operation: $RM -r $JBOSS_HOME"
  else
    $RM    $ANA_TAR_FILE
	  $RM -r $BNI
    $RM -r $JBOSS_HOME
  fi
}

is_jboss_started()
{
  info "is_jboss_started"
  if [ ! -z "$NO_EXEC" ]; then
    info "Skipping Operation: "
  else
    result=`$JBOSS_HOME/bin/twiddle.sh get "jboss.system:type=Server" Started | sed -e 's/Started=//'`
    if [ "$result" = "true" ]
    then
      return 0
    else
      return 1
    fi
  fi
}

start_jboss()
{
  if [ ! -z "$NO_EXEC" ] ; then
    info "Skipping Operation: 'start_jboss'"
  else
    if is_jboss_started
    then
      info "JBoss is already running."
      grep -A5 -B1 ERROR $JBOSS_HOME/server/default/log/server.log
      return 0
    fi
	  sudo $INIT_DIR/jboss start
  	#Waiting JMX service to start
	  sleep 60

  	#Wait for 5 minutes(15*20), check every 15 seconds
	
  	for (( i=1; i<=20; i++ ))
	  do
		  info "Waiting 15 seconds..."
		  sleep 15
		  if is_jboss_started
		  then
          grep -A5 -B1 ERROR $JBOSS_HOME/server/default/log/server.log
			  return 0
		  fi
	  done
  	exit 1
  fi
}

stop_jboss()
{
  if [ ! -z "$NO_EXEC" ] ; then
    info "Skipping Operation: 'stop_jboss'"
  else
    if is_jboss_started
    then
      sudo kill -9 `ps ax|grep jboss|awk '{print $1}'|tr "\n" " "`
    fi
  fi
}

deploy_annapurna_simulators()
{
  if [ ! -z "$NO_EXEC" ] ; then
    info "Skipping Operation: Getting '$HUDSON_URL' from Hudson"
    info "Skipping Operation: $WGET $HUDSON_URL"
    info "Skipping Operation: $TAR $BNINET_HOME/$ANA_TAR_FILE"
    info "Skipping Operation: sed -i \"s:127.0.0.1:$SIM_IP:\" $BNI_CONF/catvsim.properties"
    info "Skipping Operation: sed -i -e \"/8080/ s:localhost:$SM_HOST:\" -e \"s:8180:8080:\"  -e \" s:127.0.0.1:$SIM_IP:\"  $BNI_CONF/adssim.properties"
  else
    if [ ! -d $BNI ]; then
  	  mkdir -p $BNI
    fi
	  info "Getting '$HUDSON_URL' from Hudson"
	  exit_on_error "$WGET $HUDSON_URL"
    exit_on_error "$TAR $BNINET_HOME/$ANA_TAR_FILE" 

    if [ ! -d $BNI_CONF ]; then
      mkdir -p $BNI_CONF
    fi

    info "Deploy simulator"
    sed -i "s:127.0.0.1:$SIM_IP:" $BNI_CONF/catvsim.properties
    sed -i -e "/8080/ s:localhost:$SM_HOST:" -e "s:8180:8080:"  -e " s:127.0.0.1:$SIM_IP:"  $BNI_CONF/adssim.properties 
  fi
}

deploy_self()
{
  if [ ! -z "$NO_EXEC" ] ; then
    info "Skipping Operation: Deploy Self"
    info "Skipping Operation: ssh $BNI_USER@$SIM_HOST cd ~;rm -f ./$0 ./$FUNCTIONS"
    info "Skipping Operation: scp $0 $BNI_USER@$SIM_HOST:~"
    info "Skipping Operation: scp $FUNCTIONS $BNI_USER@$SIM_HOST:~"
    info "Skipping Operation: ssh $BNI_USER@$SM_HOST cd ~;chmod +w $FUNCTIONS $0"
    info "Skipping Operation: ssh $BNI_USER@$SIM_HOST cd ~;./$0 $DEPLOY_ARGS"
  else
    ssh $BNI_USER@$SIM_HOST "cd ~;rm -f ./$0 ./$FUNCTIONS"
    scp $0 $BNI_USER@$SIM_HOST:~
    scp $FUNCTIONS $BNI_USER@$SIM_HOST:~
    ssh $BNI_USER@$SIM_HOST "cd ~;chmod +w $FUNCTIONS $0"
    ssh $BNI_USER@$SIM_HOST "cd ~;./$0 $DEPLOY_ARGS"
  fi
  exit $?
}

exit_on_error()
{
	COMMAND=$1
	echo ">$COMMAND"
	$COMMAND
	if [ $? -ne 0 ] 
	then 
		exit 1
	fi
}


#MAIN

# Remove Old Log
$RM $LOG

# process Optional ARGS
# Process OPTIONS
DBG_OPT=
OPTS_DONE=no
while [ "$#" -gt 0 -a "$OPTS_DONE" = "no" ] ; do
  case "$1" in
  -h|-H|-help|--help)
    print_help
    exit 0
    ;;
  -D)
    DBG_ME=yes
    DEPLOY_ARGS="$DEPLOY_ARGS -D"
    shift
    ;;
  -X)
    NO_EXEC=yes
    DEPLOY_ARGS="$DEPLOY_ARGS -X"
    shift
    ;;
  -deploy)
    DEPLOY=yes
    shift
    ;;
  -jobPrefix)
    shift
    if [ -z "$1" ] ; then
      die "Missing value for -jobPrefix"
    fi
    JOB_PREFIX=$1
    DEPLOY_ARGS="$DEPLOY_ARGS -jobPrefix $1"
    shift
    ;;
  *)
    OPTS_DONE=yes
    ;;
  esac
done


# process REQUIRED_ARGS
while [ "$#" -gt 0 ] ; do
  case "$1" in
    -h|--help)
      shift
      print_help
      exit 0
      ;;
    -sim)
      shift
      if [ -z "$1" ] ; then
        die "Missing value for 'sim' argument"
      fi
      SIM_HOST=$1
      DEPLOY_ARGS="$DEPLOY_ARGS -sim $1"
      shift
      ;;
    -sm)
      shift
      if [ -z "$1" ] ; then
        die "Missing value for 'sm' argument"
      fi
      SM_HOST=$1
      DEPLOY_ARGS="$DEPLOY_ARGS -sm $1"
      shift
      ;;
    -version)
      shift
      if [ -z "$1" ] ; then
        die "Missing value for '-version' argument"
      fi
      VERSION=$1
      DEPLOY_ARGS="$DEPLOY_ARGS -version $1"
      shift
      ;;
    *)
      info "MAKE SURE OPTIONS ARE SPEIFICED BEFORE REQUIRED ARGS"
      die "Unknown argument '$1'"
      ;;
  esac
done

[ -z "$SIM_HOST" ] && print_help
[ -z "$SM_HOST" ] && print_help
[ -z "$VERSION" ] && print_help

# DYNAMIC ARGS
#Hudson
HUDSON_ADDR=http://10.10.10.11:8080
SIM_HUDSON_BASE_JOB=Annapurna-sim
SIM_HUDSON_JOB=$JOB_PREFIX$SIM_HUDSON_BASE_JOB

ANA_TAR_FILE=catv-sim-$VERSION.tar.gz
HUDSON_URL=$HUDSON_ADDR/job/$SIM_HUDSON_JOB/lastSuccessfulBuild/artifact/prodbuild/catv-sim/uber-tar/$ANA_TAR_FILE

# deploy the script
if [ ! -z "$DEPLOY" ]; then
  deploy_self
fi

export JBOSS_HOME=$JBOSS_HOME
export JAVA_HOME=/usr/java/default

stop_jboss
clean
deploy_annapurna_simulators
start_jboss

